from flask import Flask
from flask_apscheduler import APScheduler
from flask_cors import CORS
from dotenv import load_dotenv
from config import config_env
from epp.api import register_blueprint
from job import register_scheduler_task
from epp.middleware import register_middleware
from .db import db, r
from .schemas import ma
from .utils.logger import LogHandle
from .utils.cache import cache
import os

logger = LogHandle()
cors = CORS()

load_dotenv(override=True)
FLASK_ENV = os.getenv("FLASK_ENV")


def create_app() -> Flask:
    app = Flask(__name__, static_folder='../uploads')
    app.config.from_object(config_env[FLASK_ENV])

    register_from_app(app)
    init_from_app(app)

    with app.app_context():
        from .models import create_model
        create_model()

    return app


def register_from_app(app: Flask):
    register_blueprint(app)
    register_middleware(app)


def init_from_app(app: Flask):
    cors.init_app(app)
    db.init_app(app)
    r.init_app(app)
    ma.init_app(app)
    cache.init_app(app)
    logger.init_app(app)